package com.knowif.util;

import com.alibaba.fastjson.JSONObject;
import com.knowif.util.commonUtil.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

@Component
@Slf4j
public class WechatMiniUtil {
    @Value("${wechat.config.constant.key}")
    private String key;
    @Value("${wechat.config.constant.mchId}")
    private String mchId;
    @Value("${wechat.config.constant.appid}")
    private String appid;
    @Value("${wechat.config.constant.appSecret}")
    private String appSecret;
    @Value("${wechat.config.constant.templateId}")
    private String templateId;
    @Value("${wechat.config.constant.weChatAppid}")
    private String wechatAppid;
    @Value("${wechat.config.constant.weChatAppSecret}")
    private String wechatAppSecret;
    @Autowired
    private ServletContext servletContext;


    public String getInfoWechat(String api) {
        String result = "";
        try {
            URL url = new URL(api);
            InputStream in = url.openStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String temp = "";
            while((temp = br.readLine())!=null) {
                result += temp;
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 小程序获取CodeSession
     * */
    public String getCodeSession(String jsCode) {
        String result = "";
        String api = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+appSecret+"&js_code="+jsCode+"&grant_type=authorization_code";
        result = getInfoWechat(api);
        return result;
    }
    /**
     * 小程序获取access_token
     * */
    public String getAccessToken(){
        String result = "";
        String api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appSecret+"&grant_type=authorization_code";
        result = getInfoWechat(api);
        JSONObject json = JSONObject.parseObject(result);
        result = json.getString("access_token");
        return result;
    }

    /**
     * 公众号获取access_token
     * */
    public String getPlatformAccessToken(){
        String result = "";
        String api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+wechatAppid+"&secret="+wechatAppSecret;
        result = getInfoWechat(api);
        JSONObject json = JSONObject.parseObject(result);
        result = json.getString("access_token");
        return result;
    }

    public JSONObject getWeChatUserInfo(String openid){
        String result = "";
        String accessToken = (String) servletContext.getAttribute("wechatAccessToken");
        String api = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        api = api.replace("ACCESS_TOKEN",accessToken).replace("OPENID",openid);
        result = getInfoWechat(api);
        JSONObject obj = JSONObject.parseObject(result);
        int subscribe = obj.getInteger("subscribe");
        if(subscribe == 0){
            return null;
        }
        return obj;
    }

    public String sendMessageService(String openid,String formId,String info,String desc,String page) {
        System.out.println("formId ============================>"+formId );
        String result = "";
        String accessToken = (String) servletContext.getAttribute("accessToken");
        String api = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+accessToken;
        JSONObject json = new JSONObject();
        JSONObject data = new JSONObject();
        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", info);
        data.put("keyword1", keyword1);
        JSONObject keyword2 = new JSONObject();
        keyword2.put("value",new Date());
        data.put("keyword2", keyword2);

        JSONObject keyword3 = new JSONObject();
        keyword3.put("value",desc);
        data.put("keyword3", keyword3);

        json.put("template_id", "_Yjx5RMIP7MoLDaCQTY3SlR37M2-qpGwXY4ux7hOzmE");//模板信息
        json.put("page",page);
        json.put("touser", openid);
        json.put("form_id", formId);
        json.put("data", data);
        try {
            URL url = new URL(api);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setDefaultUseCaches(false);
            OutputStream out = con.getOutputStream();
            out.write(json.toJSONString().getBytes());
            InputStream in = con.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String temp = "";
            while((temp = br.readLine()) != null) {
                result += temp;
            }
            System.out.println(result);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    public void sendTemplate(String accessToken,String firstStr, String openid, List<Map<String,String>> mapList, String remarkStr, int userOrderId,String template){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser",openid);
        //jsonObject.put("template_id" ,"aAHXrdimu2RvNCyb9RhrS4orELCrAG7i3N6ZY4Za2sE");
        jsonObject.put("template_id" ,template);
        JSONObject mini = new JSONObject();
        mini.put("appid",appid);
        mini.put("pagepath","/myPages/process/process?userOrderId="+userOrderId);
        jsonObject.put("miniprogram",mini);
        JSONObject data = new JSONObject();
        JSONObject first = new JSONObject();
        first.put("value",firstStr);
        if(mapList != null && !mapList.isEmpty()){
            int index = 1;
            for(Map<String,String> map:mapList){
                data.put("keyword"+index,map);
                index++;
            }
        }
        JSONObject remark = new JSONObject();
        remark.put("value",remarkStr);

        data.put("first",first);

        data.put("remark",remark);
        jsonObject.put("data" ,data);

        try {
            URL url = new URL("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            OutputStream out = connection.getOutputStream();
            out.write(jsonObject.toJSONString().getBytes());
            out.flush();
            out.close();

            InputStream in = connection.getInputStream();
            String temp = "";
            String result = "";
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            while ((temp = br.readLine()) != null){
                result += temp;
            }
            System.out.println(result);
            in.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        List<Map<String, String>> list = new LinkedList<>();
//        Map<String, String> map1 = new HashMap<>();
//        list = new LinkedList<>();
//        map1 = new HashMap<>();
//        map1.put("value", "10");
//        list.add(map1);
//        map1 = new HashMap<>();
//        map1.put("value", "快问订单1");
//        list.add(map1);
//        map1 = new HashMap<>();
//        map1.put("value", SecurityUtil.stringToMD5("DASDJJ2J1312312MK"));
//        list.add(map1);
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("touser","oKqWu5oAhgs5od0wBI9tRWCxspaA");
//        jsonObject.put("template_id" ,"x-nMYhknvGkJq256WczOxg1cih9wm2LZMp9nnDS6CMg");
////        jsonObject.put("template_id" ,template);
//        JSONObject mini = new JSONObject();
//        mini.put("appid","wxc960ecd177075489");
//        mini.put("pagepath","/myPages/Reply/Reply");
//        jsonObject.put("miniprogram",mini);
//        JSONObject data = new JSONObject();
//        JSONObject first = new JSONObject();
//        first.put("value","导师您好，您有一个新的快问订单！");
//        if(list != null && !list.isEmpty()){
//            int index = 1;
//            for(Map<String,String> map:list){
//                data.put("keyword"+index,map);
//                index++;
//            }
//        }
//        JSONObject remark = new JSONObject();
//        remark.put("value","如在48小时未处理订单，系统将自动取消该订单。立即进入订单详情！");
//
//        data.put("first",first);
//
//        data.put("remark",remark);
//        jsonObject.put("data" ,data);
//
//        try {
//            URL url = new URL("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=26_oL_X9MoXQ-UtJJ3kub4emGKXcdG6jcBgmcnfBqcvHXnpFjZVPfyh5HNOwCqee3swFA5ammfvMW9AHEEtBsUdcZPE3EexOWibTAIQVI2PmuIYsHGIQMjNSSAQkA01GpcMBGAiIth7jJu-EHpBHUFbAEASFQ");
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//            connection.setRequestMethod("POST");
//            connection.setDoInput(true);
//            connection.setDoOutput(true);
//            connection.setUseCaches(false);
//            OutputStream out = connection.getOutputStream();
//            out.write(jsonObject.toJSONString().getBytes());
//            out.flush();
//            out.close();
//
//            InputStream in = connection.getInputStream();
//            String temp = "";
//            String result = "";
//            BufferedReader br = new BufferedReader(new InputStreamReader(in));
//            while ((temp = br.readLine()) != null){
//                result += temp;
//            }
//            log.info("发送快问模板通知" + result);
//            in.close();
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 快问订单消息模板发送
     * @param accessToken
     * @param firstStr
     * @param openid
     * @param mapList
     * @param remarkStr
     * @param pagepath
     * @param template
     */
    public void sendFATemplate(String accessToken,String firstStr, String openid, List<Map<String,String>> mapList, String remarkStr, String pagepath,String template){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser",openid);
        jsonObject.put("template_id" ,template);
        JSONObject mini = new JSONObject();
        mini.put("appid",appid);
        mini.put("pagepath",pagepath);
        jsonObject.put("miniprogram",mini);
        JSONObject data = new JSONObject();
        JSONObject first = new JSONObject();
        first.put("value",firstStr);
        if(mapList != null && !mapList.isEmpty()){
            int index = 1;
            for(Map<String,String> map:mapList){
                data.put("keyword"+index,map);
                index++;
            }
        }
        JSONObject remark = new JSONObject();
        remark.put("value",remarkStr);

        data.put("first",first);

        data.put("remark",remark);
        jsonObject.put("data" ,data);

        try {
            URL url = new URL("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            OutputStream out = connection.getOutputStream();
            out.write(jsonObject.toJSONString().getBytes());
            out.flush();
            out.close();

            InputStream in = connection.getInputStream();
            String temp = "";
            String result = "";
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            while ((temp = br.readLine()) != null){
                result += temp;
            }
            log.info("发送快问模板通知" + result);
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //xCMAcTm5WMYY8MIJpxDDNKUnMNKEIyDHRFAH73mLdqXZUS6Ax_iUqermyNFlIra5
    // 小程序客服通知
    /*public static void sendCustomerServiceMessage(String accessToken,String openid,String msgType,
            String content,String image){
        try {
            URL url = new URL("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("access_token",accessToken);
            jsonObject.put("touser",openid);
            jsonObject.put("msgtype",msgType);
            if(msgType.equals("image")){
                JSONObject img = new JSONObject();
                img.put("media_id", image);
                jsonObject.put("image",img);
            }
            if(msgType.equals("content")){
                jsonObject.put("content",content);
            }
            OutputStream out = connection.getOutputStream();
            out.write(jsonObject.toJSONString().getBytes());
            out.flush();
            out.close();

            InputStream in = connection.getInputStream();
            String temp = "";
            String result = "";
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            while ((temp = br.readLine()) != null){
                result += temp;
            }
            System.out.println(result);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }*/

}
